<?php

namespace app\index\service;

use think\facade\Session;

class DialogService extends BaseService
{
    /**
     * 获取access_token
     * @author  messha1r
     * @date    2025-09-10
     * @param   string $appid    
     * @param   string $secret    
     * @return  string     
     */
    public function getAccessToken(): string
    {
        $access_token = Session::get('access_token');
        if (!empty($access_token)) {
            return $access_token;
        }

        $url = 'https://api.weixin.qq.com/cgi-bin/token';
        $url .= '?grant_type=client_credential';
        $url .= '&appid=' . $this->appId;
        $url .= '&secret=' . $this->secret;
        // {"errcode":40013,"errmsg":"invalid appid rid: 68c140ed-472ee01e-1a245d8c"}
        // {"access_token":"96_TC8vbIETi3vNUOoyXjQKfzbQjMdaCuEQRWUsFDJtlj9-z35MqMSrdAQpI5iOkd3MqVw9ORxRlueU-E4D-N-d5NHCm93bsAJ2dCW9euL-_VqDZJxsKh4VINwldGsBLNeAFALVX","expires_in":7200}
        $data = file_get_contents($url);
        $token = json_decode($data, true);
        if (!isset($token['errcode']) && $token['access_token']) {
            Session::set('access_token', $token['access_token']);
            return $token['access_token'];
        } else {
            echo '发生错误，错误码' . $token['errcode'] . '，错误内容' . $token['errmsg'];
            return '';
        }
    }

    /**
     * 创建自定义菜单
     * @author  messha1r
     * @date    2025-09-10
     * @param        
     * @param        
     * @return array 
     */
    public function createMenu(): array
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create';
        $url .= '?access_token=' . $this->getAccessToken();

        $menu = [
            'button' => [
                ['type' => 'click', 'name' => '歌曲', 'key' => 'V1001_TODAY_MUSIC'],
                // ['type'=>'click','name'=>'对话']
            ]
        ];
        $data = \Curl::post($url, json_encode($menu, JSON_UNESCAPED_UNICODE));
        // "{"errcode":0,"errmsg":"ok"}"
        $res = json_decode($data, true);
        if ($res['errcode'] == 0) {
            return ['err_code' => 0, 'msg' => '创建菜单成功'];
        } else {
            return ['err_code' => $res['errcode'], 'msg' => $res['errmsg']];
        }
    }
}
